﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UDS.Web.UI.Controls
{
    public class RegexTextBox : RequiredTextBox
    {
        private RegularExpressionValidator _regexValidator;

        /// <summary>
        /// Get or set the error message displayed when the input format is invalid.
        /// </summary>
        [PersistenceMode(PersistenceMode.Attribute)]
        [DefaultValue("(*)")]
        public string InvalidFormatErrorMessage
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the regular expression that determines the pattern used to validate a field
        /// </summary>
        [PersistenceMode(PersistenceMode.Attribute)]
        public virtual string Regex
        {
            get;
            set;
        }

        public RegexTextBox()
        {
            InvalidFormatErrorMessage = "(*)";
        }

        /// <summary>
        /// Init the control
        /// </summary>
        protected override void OnInit(EventArgs e)
        {
            _regexValidator = new RegularExpressionValidator();
            _regexValidator.ControlToValidate = ID;
            _regexValidator.ValidationExpression = Regex;
            InitValidator(_regexValidator, InvalidFormatErrorMessage, ErrorCssClass);
            Controls.Add(_regexValidator);

            base.OnInit(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);

            Debug.Assert(_regexValidator != null);

            writer.WriteLine();
            _regexValidator.RenderControl(writer);
        }
    }
}
